<template>
	<div class="sales-order-detail" v-loading="loading">
		<div class="page-header">
			<div class="header-content">
				<el-button @click="goBack" icon="ArrowLeft" type="primary" plain>返回列表</el-button>
				<h2>销售订单详情</h2>
				<div class="header-actions">
					<el-button @click="editOrder" type="primary" icon="Edit" v-if="detail?.orderStatus === '草稿'">编辑</el-button>
					<el-button @click="openShip" type="primary" plain>出库</el-button>
					<el-button @click="openReceive" type="success" plain>收款</el-button>
					<el-button @click="openInvoice" type="warning" plain>开票</el-button>
				</div>
			</div>
		</div>

		<!-- 顶部基本信息卡片 -->
		<el-card class="detail-card" shadow="never">
			<template #header>
				<div class="card-header">
					<span>订单信息</span>
					<el-tag :type="getStatusType(detail?.orderStatus)" size="large">{{ detail?.orderStatus }}</el-tag>
				</div>
			</template>
			<el-descriptions :column="2" border>
				<el-descriptions-item label="订单主题">{{ detail?.orderSubject }}</el-descriptions-item>
				<el-descriptions-item label="订单编号">{{ detail?.salesOrderNumber }}</el-descriptions-item>
				<el-descriptions-item label="客户名称">{{ detail?.customerName }}</el-descriptions-item>
				<el-descriptions-item label="订单日期">{{ formatDate(detail?.salesDate) }}</el-descriptions-item>
				<el-descriptions-item label="联系人">{{ detail?.contactPerson || '-' }}</el-descriptions-item>
				<el-descriptions-item label="联系电话">{{ detail?.contactPhone || '-' }}</el-descriptions-item>
				<el-descriptions-item label="结算方式">{{ detail?.settlementMethod || '-' }}</el-descriptions-item>
				<el-descriptions-item label="交货地址" :span="2">{{ detail?.deliveryAddress || '-' }}</el-descriptions-item>
				<el-descriptions-item label="备注" :span="2">{{ detail?.remarks || '-' }}</el-descriptions-item>
			</el-descriptions>
		</el-card>

		<!-- 物品明细 -->
		<el-card class="detail-card" shadow="never">
			<template #header>
				<div class="card-header">
					<span>物品明细</span>
					<div>
						<el-button size="small" @click="exportDetailsExcel" icon="Document">导出</el-button>
					</div>
				</div>
			</template>
			<el-table :data="orderDetails" border stripe>
				<el-table-column type="index" label="#" width="60" />
				<el-table-column prop="itemNumber" label="物品编号" width="150" />
				<el-table-column prop="itemName" label="物品名称" min-width="200" show-overflow-tooltip />
				<el-table-column prop="specificationModel" label="规格型号" width="150" />
				<el-table-column prop="unit" label="单位" width="100" />
				<el-table-column prop="salesQuantity" label="销售数量" width="120" />
				<el-table-column prop="unitPriceIncludingTax" label="含税单价" width="120">
					<template #default="{ row }">¥{{ formatNumber(row.unitPriceIncludingTax) }}</template>
				</el-table-column>
				<el-table-column prop="taxRate" label="税率" width="100">
					<template #default="{ row }">{{ row.taxRate }}%</template>
				</el-table-column>
				<el-table-column prop="amountIncludingTax" label="含税金额" width="120">
					<template #default="{ row }">¥{{ formatNumber(row.amountIncludingTax) }}</template>
				</el-table-column>
				<el-table-column prop="remarks" label="备注" min-width="150" show-overflow-tooltip />
			</el-table>
			<div class="total-info">
				<el-row :gutter="20">
					<el-col :span="6"><span class="total-label">明细数量：</span><span class="total-value">{{ orderDetails.length }}</span></el-col>
					<el-col :span="6"><span class="total-label">含税总额：</span><span class="total-value">¥{{ formatNumber(totalAmountIncludingTax) }}</span></el-col>
					<el-col :span="6"><span class="total-label">不含税总额：</span><span class="total-value">¥{{ formatNumber(totalAmountExcludingTax) }}</span></el-col>
					<el-col :span="6"><span class="total-label">税额：</span><span class="total-value">¥{{ formatNumber(totalAmountIncludingTax - totalAmountExcludingTax) }}</span></el-col>
				</el-row>
			</div>
		</el-card>

		<!-- 记录 Tabs -->
		<el-card class="detail-card" shadow="never">
			<el-tabs v-model="activeTab">
				<el-tab-pane label="出库记录" name="ship">
					<div style="margin-bottom:10px">
						<el-button size="small" @click="exportShip">导出</el-button>
					</div>
					<el-table :data="shipRecords" border stripe v-loading="tabLoading">
						<el-table-column type="index" label="#" width="60" />
						<el-table-column prop="code" label="单号" width="160" />
						<el-table-column prop="subject" label="主题" min-width="200" />
						<el-table-column prop="date" label="日期" width="140" />
						<el-table-column prop="qty" label="数量" width="100" />
						<el-table-column prop="amount" label="金额" width="120" />
						<el-table-column label="操作" width="100">
							<template #default>查看</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="收款记录" name="receive">
					<div style="margin-bottom:10px">
						<el-button size="small" @click="exportReceive">导出</el-button>
					</div>
					<el-table :data="receiveRecords" border stripe v-loading="tabLoading">
						<el-table-column type="index" label="#" width="60" />
						<el-table-column prop="code" label="单号" width="160" />
						<el-table-column prop="subject" label="主题" min-width="200" />
						<el-table-column prop="date" label="日期" width="140" />
						<el-table-column prop="qty" label="数量" width="100" />
						<el-table-column prop="amount" label="金额" width="120" />
						<el-table-column label="操作" width="100">
							<template #default>查看</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="开票记录" name="invoice">
					<div style="margin-bottom:10px">
						<el-button size="small" @click="exportInvoice">导出</el-button>
					</div>
					<el-table :data="invoiceRecords" border stripe v-loading="tabLoading">
						<el-table-column type="index" label="#" width="60" />
						<el-table-column prop="code" label="单号" width="160" />
						<el-table-column prop="subject" label="主题" min-width="200" />
						<el-table-column prop="date" label="日期" width="140" />
						<el-table-column prop="qty" label="数量" width="100" />
						<el-table-column prop="amount" label="金额" width="120" />
						<el-table-column label="操作" width="100">
							<template #default>查看</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="生产记录" name="produce">
					<div style="margin-bottom:10px">
						<el-button size="small" @click="exportProduce">导出</el-button>
					</div>
					<el-table :data="produceRecords" border stripe v-loading="tabLoading">
						<el-table-column type="index" label="#" width="60" />
						<el-table-column prop="code" label="单号" width="160" />
						<el-table-column prop="subject" label="主题" min-width="200" />
						<el-table-column prop="date" label="日期" width="140" />
						<el-table-column prop="qty" label="数量" width="100" />
						<el-table-column prop="amount" label="金额" width="120" />
						<el-table-column label="操作" width="100">
							<template #default>查看</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="退货记录" name="return">
					<div style="margin-bottom:10px">
						<el-button size="small" @click="exportReturn">导出</el-button>
					</div>
					<el-table :data="returnRecords" border stripe v-loading="tabLoading">
						<el-table-column type="index" label="#" width="60" />
						<el-table-column prop="code" label="单号" width="160" />
						<el-table-column prop="subject" label="主题" min-width="200" />
						<el-table-column prop="date" label="日期" width="140" />
						<el-table-column prop="qty" label="数量" width="100" />
						<el-table-column prop="amount" label="金额" width="120" />
						<el-table-column label="操作" width="100">
							<template #default>查看</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="采购记录" name="purchase">
					<div style="margin-bottom:10px">
						<el-button size="small" @click="exportPurchase">导出</el-button>
					</div>
					<el-table :data="purchaseRecords" border stripe v-loading="tabLoading">
						<el-table-column type="index" label="#" width="60" />
						<el-table-column prop="code" label="单号" width="160" />
						<el-table-column prop="subject" label="主题" min-width="200" />
						<el-table-column prop="date" label="日期" width="140" />
						<el-table-column prop="qty" label="数量" width="100" />
						<el-table-column prop="amount" label="金额" width="120" />
						<el-table-column label="操作" width="100">
							<template #default>查看</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="操作记录" name="operation">
					<el-timeline>
						<el-timeline-item v-for="record in operationRecords" :key="record.id" :timestamp="new Date(record.operationTime).toLocaleString('zh-CN')" type="primary">
							<h4>{{ record.operationType }}</h4>
							<p>{{ record.operationContent }}</p>
						</el-timeline-item>
					</el-timeline>
				</el-tab-pane>
			</el-tabs>
		</el-card>

		<!-- 编辑对话框 -->
		<el-dialog v-model="editDialogVisible" title="编辑销售订单" width="80%" :close-on-click-modal="false" :close-on-press-escape="false">
			<SalesOrderForm ref="formRef" :form-data="detail || {}" :is-edit="true" @submit="handleUpdate" @cancel="editDialogVisible = false" />
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { salesOrderApi } from '@/api/salesOrderApi'
import type { SalesOrderDetailResponse } from '@/types/salesOrder'
import SalesOrderForm from './SalesOrderForm.vue'
import * as XLSX from 'xlsx'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const tabLoading = ref(false)
const detail = ref<SalesOrderDetailResponse | null>(null)
const editDialogVisible = ref(false)
const formRef = ref()

const activeTab = ref('ship')

// 记录数据（示例/占位，无查询条件）
const shipRecords = ref<any[]>([])
const receiveRecords = ref<any[]>([])
const invoiceRecords = ref<any[]>([])
const produceRecords = ref<any[]>([])
const returnRecords = ref<any[]>([])
const purchaseRecords = ref<any[]>([])

// 模拟操作记录数据
const operationRecords = ref([
	{ id: 1, operationType: '创建', operationContent: '创建销售订单', operatorName: '张三', operationTime: new Date().toISOString(), ipAddress: '127.0.0.1' }
])

onMounted(() => {
	loadDetail()
})

watch(activeTab, () => loadTabData())

const loadDetail = async () => {
	try {
		loading.value = true
		const id = Number(route.params.id)
		const res = await salesOrderApi.getById(id)
		if (res.code === 200) {
			detail.value = res.data
			// 首次也加载一下标签数据
			await loadTabData()
		} else {
			ElMessage.error(res.message || '获取详情失败')
		}
	} catch (error: any) {
		ElMessage.error(error.message || '获取详情失败')
	} finally {
		loading.value = false
	}
}

const loadTabData = async () => {
	try {
		tabLoading.value = true
		const base = (n: string) => ({ code: `${n}${Date.now().toString().slice(-6)}`, subject: `${n}主题`, date: new Date().toISOString().slice(0,10), qty: 50, amount: 5000 })
		shipRecords.value = Array.from({ length: 5 }, (_, i) => ({ ...base('CK'), qty: 50 }))
		receiveRecords.value = Array.from({ length: 5 }, () => ({ ...base('SRDD'), amount: 45234 }))
		invoiceRecords.value = Array.from({ length: 5 }, () => ({ ...base('KPDD'), amount: 35156 }))
		produceRecords.value = Array.from({ length: 5 }, () => ({ ...base('SRDD'), qty: 50 }))
		returnRecords.value = Array.from({ length: 5 }, () => ({ ...base('RKDH'), qty: 10 }))
		purchaseRecords.value = Array.from({ length: 5 }, () => ({ ...base('CGRK'), qty: 10 }))
	} finally {
		tabLoading.value = false
	}
}

const totalAmountIncludingTax = computed(() => {
	const items = (detail.value as any)?.orderDetails || (detail.value as any)?.details || []
	return items.reduce((sum: number, d: any) => sum + (d.amountIncludingTax || 0), 0)
})

const totalAmountExcludingTax = computed(() => {
	const items = (detail.value as any)?.orderDetails || (detail.value as any)?.details || []
	return items.reduce((sum: number, d: any) => sum + (d.amountExcludingTax || 0), 0)
})

const orderDetails = computed(() => {
	if (!detail.value) return []
	const details = detail.value.orderDetails || (detail.value as any)?.details || []
	return Array.isArray(details) ? details : []
})

const editOrder = () => { editDialogVisible.value = true }

const handleUpdate = async (data: any) => {
	try {
		loading.value = true
		const res = await salesOrderApi.update(data)
		if (res.code === 200) {
			ElMessage.success('更新成功')
			editDialogVisible.value = false
			loadDetail()
		} else {
			ElMessage.error(res.message || '更新失败')
		}
	} catch (error: any) {
		ElMessage.error(error.message || '更新失败')
	} finally {
		loading.value = false
	}
}

// 导出
function toExcel(rows: any[], name: string) {
	const ws = XLSX.utils.json_to_sheet(rows)
	const wb = XLSX.utils.book_new()
	XLSX.utils.book_append_sheet(wb, ws, name)
	const ts = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')
	XLSX.writeFile(wb, `${name}-${ts}.xlsx`)
}
const exportDetailsExcel = () => toExcel(orderDetails.value as any, '销售订单明细')
const exportShip = () => toExcel(shipRecords.value, '出库记录')
const exportReceive = () => toExcel(receiveRecords.value, '收款记录')
const exportInvoice = () => toExcel(invoiceRecords.value, '开票记录')
const exportProduce = () => toExcel(produceRecords.value, '生产记录')
const exportReturn = () => toExcel(returnRecords.value, '退货记录')
const exportPurchase = () => toExcel(purchaseRecords.value, '采购记录')

// 打开动作（占位）
const openShip = () => ElMessage.info('出库功能占位')
const openReceive = () => ElMessage.info('收款功能占位')
const openInvoice = () => ElMessage.info('开票功能占位')

const goBack = () => { router.push('/SalesOrderList') }

// 工具函数
const formatDate = (date?: string) => (date ? new Date(date).toLocaleDateString('zh-CN') : '-')
const formatNumber = (num: number) => (num ? num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '0.00')
const getStatusType = (status?: string) => {
	switch (status) {
		case '已完成':
		case '已审批':
			return 'success'
		case '审批中':
		case '待审批':
			return 'warning'
		case '已提交':
			return 'info'
		case '驳回':
		case '已取消':
			return 'danger'
		default:
			return 'info'
	}
}
</script>

<style scoped>
.sales-order-detail { padding: 20px; }
.page-header { margin-bottom: 16px; }
.header-content { display: flex; align-items: center; gap: 16px; }
.header-content h2 { margin: 0; flex: 1; }
.header-actions { display: flex; gap: 8px; }
.detail-card { margin-bottom: 16px; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
.detail-count { color: #909399; font-size: 14px; }
.total-info { margin-top: 20px; padding: 16px; background-color: #f5f7fa; border-radius: 4px; }
.total-label { font-weight: bold; color: #606266; }
.total-value { font-size: 16px; color: #409eff; font-weight: bold; }
</style> 